package cn.z2huo.knowledge.concurrency.producerconsumer;

import cn.hutool.core.thread.ThreadUtil;

import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * <p>
 *
 * @author z2huo
 */
public class Consumer implements Runnable {

    /**
     * 消费的时间间隔，默认等待100毫秒
     */
    public static final int CONSUME_GAP = 100;

    /**
     * 消费总次数
     */
    static final AtomicInteger TURN = new AtomicInteger(1);

    /**
     * 消费者对象编号，从 1 开始
     */
    static final AtomicInteger CONSUMER_NO = new AtomicInteger(1);

    /**
     * 消费者名称
     */
    private String name;

    /**
     * 消费的动作
     */
    private Callable<?> action = null;

    /**
     * 消费一次等待的时间，默认为 100 毫秒
     */
    private int gap = CONSUME_GAP;

    public Consumer(Callable<?> action) {
        this(action, CONSUME_GAP);
    }

    public Consumer(Callable<?> action, int gap) {
        this.action = action;
        this.gap = gap;
        name = "消费者-" + CONSUMER_NO.getAndIncrement();
    }

    @Override
    public void run() {
        while (true) {
            try {
                // 增加消费次数
                TURN.getAndIncrement();
                // 执行消费动作
                System.out.println("消费者 " + name + " 消费开始");
                Object out = action.call();
                if (null != out) {
                    System.out.println("第 " + TURN.get() + " 轮消费：" + out);
                } else {
                    System.out.println("第 " + TURN.get() + " 轮消费，无数据");
                }
                ThreadUtil.sleep(gap, TimeUnit.MILLISECONDS);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
